package controllers

import (
	"encoding/json"
	"fmt"
	ck_orm "github.com/clakeboy/ck-orm"
	"github.com/clakeboy/golib/components"
	"github.com/clakeboy/golib/utils"
	"github.com/gin-gonic/gin"
	"time"
	"urs_service/models"
)

const (
	Delete = "delete"
	New    = "new"
	Edit   = "edit"
)

type DataProcess struct {
	Table string  `json:"table"` //表名
	Type  string  `json:"type"`  //处理类型
	Data  utils.M `json:"data"`  //数据
}

func NewDataProcessingController(c *gin.Context) *DataProcessingController {
	return &DataProcessingController{c: c}
}

//数据处理
type DataProcessingController struct {
	c *gin.Context
}

func (d *DataProcessingController) ActionProcess(args []byte) (utils.M, error) {
	data := &DataProcess{}
	err := json.Unmarshal(args, data)
	if err != nil {
		return nil, err
	}

	switch data.Type {
	case New, Edit:
		return d.SaveData(data)
	case Delete:
		return d.Delete(data)
	}

	return nil, nil
}

//删除记录
func (d *DataProcessingController) Delete(data *DataProcess) (utils.M, error) {
	fields, err := d.GetTableFields(data.Table)
	if err != nil {
		return nil, err
	}
	pk := fields["PK"]
	pkVal, ok := data.Data[pk.Name]
	if !ok {
		return nil, fmt.Errorf("delete pk field error: %s is empty", pk.Name)
	}
	db := d.c.MustGet("sqlite").(*ck_orm.DBA)
	tab := db.Table(data.Table)
	ok = tab.Where(utils.M{
		pk.Name: pkVal,
	}, "").Delete()
	if !ok {
		return nil, db.LastError
	}
	return nil, nil
}

//保存数据
func (d *DataProcessingController) SaveData(data *DataProcess) (utils.M, error) {
	fields, err := d.GetTableFields(data.Table)
	if err != nil {
		return nil, err
	}

	saveData := utils.M{}
	for k, v := range fields {
		if k == "created_date" && data.Type == New {
			saveData["created_date"] = time.Now().Format("2006-01-02 15:04:05")
			saveData["modified_date"] = time.Now().Format("2006-01-02 15:04:05")
			continue
		} else if k == "modified_date" && data.Type == Edit {
			saveData["modified_date"] = time.Now().Format("2006-01-02 15:04:05")
			continue
		}
		val, ok := data.Data[k]
		if ok {
			saveData[v.Name] = val
		}
	}
	db := d.c.MustGet("sqlite").(*ck_orm.DBA)
	tab := db.Table(data.Table)
	pk := fields["PK"]
	result := utils.M{}
	utils.PrintAny(saveData)
	if data.Type == New {
		delete(saveData, pk.Name)
		insertId, ok := tab.Insert(saveData)
		if !ok {
			fmt.Println(db.LastSql, db.LastError)
			return nil, db.LastError
		}
		result["new_id"] = insertId
	} else if data.Type == Edit {
		ok := tab.Where(utils.M{
			pk.Name: saveData[pk.Name],
		}, "").Update(saveData)
		if !ok {
			return nil, db.LastError
		}
	}
	return result, nil
}

//得到表所有字段信息
func (d *DataProcessingController) GetTableFields(tableName string) (models.MapFields, error) {
	cache := d.c.MustGet("cache").(*components.MemCache)
	cacheKey := fmt.Sprintf("tab_field_%s", tableName)
	cacheResult, err := cache.Get(cacheKey)
	if err != nil {
		db := d.c.MustGet("sqlite").(*ck_orm.DBA)
		fields, err := models.GetTableFields(db, tableName)
		if err != nil {
			return nil, err
		}
		cache.Set(cacheKey, fields, -1)
		cacheResult = fields
	}

	return cacheResult.(models.MapFields), nil
}
